#! /bin/bash
#
# Init file for Golimojo server daemon
#
# chkconfig: 2345 85 15
# description: Golimojo server daemon
#

# source standard init.d utility functions
. /etc/init.d/functions

# The directory in which this script resides should be the current working directory.
# However, the script might be invoked from elsewhere via symlink: for example it
# may be symlinked from the /etc/init.d directory.
SCRIPT=$(readlink -f "$0")
SCRIPTDIR=${SCRIPT%/*}
cd "$SCRIPTDIR"

# Source the Golimojo shell config file.
. golimojo.config.sh

# Add Java directories to the path.
PATH="$JREPATH:$JDKPATH:$PATH"
export PATH

# JAVA_HOME should be defined in the config file, but we still need to export it.
export JAVA_HOME

# The utility functions expect the PID file to be in /var/run/$PIDBASENAME.pid.
PIDBASENAME=golimojo

#
# Function to start the service.
#

start()
{
  # Invoke the JRE in the background.
  java -Xmx1000m -classpath "$GCLASSPATH" com.golimojo.Service &>stdxxx.log &

  # Get the process ID for our java instance.  It's probably best to do this right away.
  # Note that "$$" is the process ID for this script, so we're asking pgrep to only look at
  # child processes of this script.  The "-n" simply means we only want the newest matching PID.
  PID=$(pgrep -n -P $$ java)
  if [ -z "$PID" ]; then
    exit 1
  else
    echo "$PID" > "/var/run/$PIDBASENAME.pid"
    exit 0
  fi
}

#
# Function to stop the service.
#

stop()
{
  killproc "$PIDBASENAME"
}

#
# Parse the argument and do the right thing.
#

case $1 in

  start)
    echo "start"
    start
    ;;

  stop)
    echo "stop"
    stop
    ;;

  restart)
    echo "restart"
    stop
    sleep 1
    start
    ;;

esac

